<template>
  <div class="pagination-container" :class="{ hidden: hidden }">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="currentPageSize"
      :page-sizes="pageSizes"
      :total="total"
      :background="background"
      :layout="layout"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'

interface Props {
  total: number
  page?: number
  limit?: number
  pageSizes?: number[]
  layout?: string
  background?: boolean
  autoScroll?: boolean
  hidden?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  page: 1,
  limit: 10,
  pageSizes: () => [10, 20, 30, 50],
  layout: 'total, sizes, prev, pager, next, jumper',
  background: true,
  autoScroll: true,
  hidden: false,
})

const emit = defineEmits<{
  pagination: [{ page: number; limit: number }]
  'update:page': [number]
  'update:limit': [number]
}>()

const currentPage = computed({
  get() {
    return props.page
  },
  set(val: number) {
    emit('update:page', val)
  },
})

const currentPageSize = computed({
  get() {
    return props.limit
  },
  set(val: number) {
    emit('update:limit', val)
  },
})

const handleSizeChange = (val: number) => {
  emit('pagination', { page: currentPage.value, limit: val })
  if (props.autoScroll) {
    scrollTo(0, 800)
  }
}

const handleCurrentChange = (val: number) => {
  emit('pagination', { page: val, limit: currentPageSize.value })
  if (props.autoScroll) {
    scrollTo(0, 800)
  }
}

const scrollTo = (to: number, duration: number) => {
  if (duration <= 0) return
  const difference = to - window.scrollY
  const perTick = (difference / duration) * 10

  setTimeout(() => {
    window.scrollTo(0, window.scrollY + perTick)
    if (window.scrollY === to) return
    scrollTo(to, duration - 10)
  }, 10)
}
</script>

<style lang="scss" scoped>
.pagination-container {
  background: #fff;
  padding: 32px 16px;
  text-align: right;

  &.hidden {
    display: none;
  }
}

.dark .pagination-container {
  background: var(--kexilo-bg-color);
}
</style>
